<template>
  <div>
    <el-form :inline="true" @submit.prevent style="margin-bottom: 10px;">
      <el-form-item label="状态:">
        <el-select v-model="query.status" placeholder="全部消息" style="width:120px">
          <el-option label="全部消息" value="" />
          <el-option label="未读" value="2" />
          <el-option label="已读" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="query.title" placeholder="请输入" style="width:180px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchList">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="msgList"
        @selection-change="onSelect"
        style="width: 100%;"
        row-key="id"
    >
      <el-table-column type="selection" width="40"/>
      <el-table-column prop="title" label="标题" min-width="180"/>
      <el-table-column prop="content" label="内容" min-width="200"/>
      <el-table-column prop="is_read" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.is_read === '2' ? 'danger' : 'success'">
            {{ scope.row.is_read === "2" ? '未读' : '已读' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="时间(UTC+8)" width="180">
        <template #default="scope">
          {{ formatTime(scope.row.created_at || scope.row.CreatedAt) }}
        </template>
      </el-table-column>
    </el-table>
    <div style="margin:10px 0;">
      <el-button @click="handleBatchDelete" :disabled="!selected.length">删除</el-button>
      <el-button @click="handleBatchMarkRead" :disabled="!selected.length">标记为已读</el-button>
      <el-button @click="handleAllDelete" :disabled="!msgList.length">全部删除</el-button>
      <el-button @click="handleAllMarkRead" :disabled="!msgList.length">全部已读</el-button>
    </div>
    <el-pagination
        v-model:current-page="query.page"
        :page-size="query.pageSize"
        :total="total"
        @current-change="fetchList"
        layout="prev, pager, next"
        style="margin-top:10px"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import {
  getUserMessages,
  markMessageRead,
  batchMarkRead as apiBatchMarkRead,
  batchDelete as apiBatchDelete,
  allMarkRead as apiAllMarkRead,
  allDelete as apiAllDelete
} from '@/api/system/site_message'
import { ElMessage } from 'element-plus'
import { useAppStore } from '@/pinia'

const appStore = useAppStore()
const msgList = ref([])
const total = ref(0)
const selected = ref([])
const unreadCount = ref(0)
const query = ref({
  status: '',
  title: '',
  page: 1,
  pageSize: 10
})

// 时间格式化函数
const formatTime = (timeStr) => {
  if (!timeStr) return '---'
  try {
    const date = new Date(timeStr)
    if (isNaN(date.getTime())) return '---'
    
    // 使用 toLocaleString 方法格式化北京时间
    return date.toLocaleString('zh-CN', {
      timeZone: 'Asia/Shanghai',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
  } catch (error) {
    return '---'
  }
}

const fetchList = async () => {
  const res = await getUserMessages(query.value)
  if (res.code === 0) {
    msgList.value = res.data.list.map(item => ({
      ...item,
      id: item.id || item.ID,
      created_at: item.created_at || item.CreatedAt
    }))
    total.value = res.data.total
  }
}
const fetchUnreadCount = async () => {
  const res = await getUserMessages({ page: 1, pageSize: 1, status: '2' })
  if (res.code === 0) {
    unreadCount.value = res.data.total
    appStore.setUnreadSiteMsgCount(res.data.total)
  }
}
const onSelect = (rows) => {
  selected.value = rows.map(row => row.id)
}
const handleBatchMarkRead = async () => {
  await apiBatchMarkRead({ ids: selected.value })
  ElMessage.success('标记成功')
  fetchList()
  fetchUnreadCount()
}
const handleBatchDelete = async () => {
  await apiBatchDelete({ ids: selected.value })
  ElMessage.success('删除成功')
  fetchList()
  fetchUnreadCount()
}
const handleAllMarkRead = async () => {
  await apiAllMarkRead()
  ElMessage.success('全部已读')
  fetchList()
  fetchUnreadCount()
}
const handleAllDelete = async () => {
  await apiAllDelete()
  ElMessage.success('全部删除')
  fetchList()
  fetchUnreadCount()
}

// WebSocket 实时刷新
let ws = null
function connectWS() {
  ws = new window.WebSocket(`ws://${window.location.hostname}:8888/site_message/ws`)
  ws.onmessage = (event) => {
    fetchList()
    fetchUnreadCount()
    ElMessage.info('有新消息')
  }
  ws.onclose = () => {
    setTimeout(connectWS, 3000)
  }
}

onMounted(() => {
  fetchList()
  fetchUnreadCount()
  connectWS()
})
onUnmounted(() => {
  if (ws) ws.close()
})
</script>